package com.sakura.probe.service.impl;



import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sakura.probe.mapper.TopicCategoryMapper;
import com.sakura.probe.mapper.TopicMapper;
import com.sakura.probe.nosql.redis.RedisKey;
import com.sakura.probe.nosql.redis.RedisService;
import com.sakura.probe.pojo.Topic;
import com.sakura.probe.pojo.TopicCategory;
import com.sakura.probe.service.TopicCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class TopicCategoryServiceImpl extends ServiceImpl<TopicCategoryMapper, TopicCategory> implements TopicCategoryService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private TopicCategoryMapper mapper;
    @Autowired
    private TopicMapper topicMapper;

    @Override
    public List<TopicCategory> getTopicCategoryList() {
        List<TopicCategory> list = null;
        if (redisService.exist(RedisKey.getTopicCategory())){
            //说明redis中存储了该数据,直接从redis中读取
            String TopicCategoryStr = redisService.get(RedisKey.getTopicCategory());
            ObjectMapper mapper = new ObjectMapper();
            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class,TopicCategory.class);
            //将相关key对应的value里的string转换成对象的实体类集合
            try {
                list = mapper.readValue(TopicCategoryStr,javaType);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }else {
            //从mysql中读取,读取后将数据存储在redis中
            list = mapper.selectList(new QueryWrapper<TopicCategory>()
                    .isNull("parent_id").orderByDesc("priority"));
            String jsonString = JSONUtil.toJsonStr(list);
            redisService.set(RedisKey.getTopicCategory(),jsonString);
        }
        return list;
    }

    @Override
    public void getTopicStaticData(Map<String, Object> modelMap) {
        LinkedList<Integer> list = new LinkedList<>();
        for (int i=1;i<=5;i++){
            Integer count = topicMapper.selectCount(new QueryWrapper<Topic>()
                    .eq("topic_category_id", i));
            list.addLast(count);
        }
        modelMap.put("topicCount",list);
    }
}
